package com.lancoo.znbkxx.base;


import com.lancoo.znbkxx.beans.RequestLogBean;
import com.lancoo.znbkxx.utils.Util;

import java.util.ArrayList;
import java.util.List;

/**
 * Create by TangJun on 2019/2/16
 */
public class NetLogger {
    private static final List<INetLogListener> logListeners = new ArrayList<>();

    public static void addLogListener(INetLogListener logListener) {
        synchronized (logListeners) {
            if (!logListeners.contains(logListener)) {
                logListeners.add(logListener);
            }
        }
    }


    public static void removeLogListener(INetLogListener logListener) {
        synchronized (logListeners) {
            if (logListeners.size() > 0) {
                if (logListeners.contains(logListener)) {
                    logListeners.remove(logListener);
                }
            }
        }

    }


    public static void removeAll() {
        synchronized (logListeners) {
            logListeners.clear();
        }
    }

    public static void onRequestLogBean(RequestLogBean logBean) {
        logBean.Mode = 3;
        onLogListener(logBean);
    }

    public static void onRequestException(String exception) {
        RequestLogBean logBean = new RequestLogBean();
        logBean.IsSuccess = false;
        logBean.Response = exception;
        logBean.Time = Util.getCurrentDateString();
        logBean.Mode = 3;
        onLogListener(logBean);
    }

    public static void onResponseByte(byte[] responseBytes) {
        onLogListener(responseBytes);
    }

    public static void onResponseString(boolean isSuccess, String responseString) {
        RequestLogBean logBean = new RequestLogBean();
        logBean.IsSuccess = isSuccess;
        logBean.Time = Util.getCurrentDateString();
        logBean.Response = responseString;
        logBean.Mode = 2;
        onLogListener(logBean);
    }


    private static void onLogListener(byte[] bytes) {
        if (logListeners.size() > 0) {
            for (INetLogListener logListener : logListeners) {
                logListener.onResponseLog(bytes);
            }
        }
    }

    private static void onLogListener(RequestLogBean logBean) {
        if (logListeners.size() > 0) {
            for (INetLogListener logListener : logListeners) {
                logListener.onRequestLog(logBean);
            }
        }
    }

}
